package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author 应癫
 */
public class ConnectionUtils {

    private static DruidDataSource dataSource = new DruidDataSource();
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/bank");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
    }
    public static Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if(connection == null){
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

//    private static final String name = "com.mysql.jdbc.Driver";
//    private static final String url = "jdbc:mysql://localhost:3306/bank";
//    private static final String username = "root";
//    private static final String password = "root";
//    private static Connection connection = null;
    //private static ConnectionUtils connectionUtils = new ConnectionUtils();

//    public static Connection getInstance() throws Exception {
//        Class.forName(name);
//        DriverManager.getConnection(url,username,password);
//        Connection con = DruidUtils.getInstance().getConnection();
//        return con;
//    }
//
//
//    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>(); // 存储当前线程的连接
//
//    /**
//     * 从当前线程获取连接
//     */
//    public Connection getCurrentThreadConn() throws SQLException {
//        /**
//         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
//          */
//        Connection connection = threadLocal.get();
//        if(connection == null) {
//            // 从连接池拿连接并绑定到线程
//            connection = DruidUtils.getInstance().getConnection();
//            // 绑定到当前线程
//            threadLocal.set(connection);
//        }
//        return connection;
//
//    }
}
